package com.zzg.common.base.helper;

import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @author guyong
 *
 */
public class Unchecked {

    public static <K, V, E extends Exception> Function<K, V> function(ThrowingFunction<K, V, E> fn) {
        return fn.uncheck();
    }

    public static <T, E extends Exception> Consumer<T> consumer(ThrowingConsumer<T, E> consumer) {
        return consumer.uncheck();
    }

    @FunctionalInterface
    public static interface ThrowingConsumer<T, E extends Exception> {
        void accept(T t) throws E;

        default Consumer<T> uncheck() {
            return t -> {
                try {
                    accept(t);
                } catch (Exception e) {
                    if (e instanceof RuntimeException) {
                        throw (RuntimeException)e;
                    }
                    throw new RuntimeException(e);
                }
            };
        };
    }

    @FunctionalInterface
    public static interface ThrowingFunction<T, R, E extends Exception> {
        R apply(T t) throws E;

        default Function<T, R> uncheck() {
            return t -> {
                try {
                    return apply(t);
                } catch (Exception e) {
                    if (e instanceof RuntimeException) {
                        throw (RuntimeException)e;
                    }
                    throw new RuntimeException(e);
                }
            };
        }
    }

}